﻿using System.Collections.Generic;
using ClientOverflow.DataTransferObjects;
using ClientOverflow.ViewModels.Interfaces;
using ClientOverflow.ViewModels.MainMenus;
using System.Linq;
using ClientOverflow.ViewModels.UserProfileViewModels;

namespace ClientOverflow.ViewModels.TagsViewModels
{
    /// <summary>
    /// TagsViewModel shows all the tags in the system. It routes the requests for specific tag to the
    /// active questions in that tag.
    /// </summary>
    public class TagsViewModel : ITagsViewModel
    {
        public TagsViewModel(IMenusViewModel viewModel)
        {
            Question[] allQuestions = GetAllQuestions();

            InitializeTagsViewModels(viewModel, allQuestions);
        }

        private void InitializeTagsViewModels(IMenusViewModel viewModel, Question[] allQuestions)
        {
            var tags = allQuestions.SelectMany(question => question.Tags).Distinct();
            var groupedTags = tags
                .GroupBy(tag => tag, tag => allQuestions.Where(question => question.Tags.Contains(tag)));
            Tags = groupedTags.Select(
                grouping =>
                TagViewModel.CreateTagViewModel(grouping.Key, grouping.Count(), viewModel,
                                                new TagQuestionsFilter(grouping.Key)))
                                                .ToList();
        }

        private Question[] GetAllQuestions()
        {
            Question[] allQuestions;
            using (var serviceClient = ServicesFactory.CreateClientOverflowServiceClient())
            {
                allQuestions = serviceClient.GetAllQuestions();
            }
            return allQuestions;
        }

        public IList<ITagViewModel> Tags { get; private set; }
    }
}
